package com.rn.ddd.domain.order.handler;

import com.rn.ddd.domain.order.entity.OrderDO;
import com.rn.ddd.domain.order.repository.OrderRepository;
import com.rn.ddd.infrastructure.base.DomainEventPublisher;
import com.rn.ddd.infrastructure.engine.AbstractStateProcessor;
import com.rn.ddd.infrastructure.engine.PluginHandler;
import com.rn.ddd.infrastructure.engine.Result;
import com.rn.ddd.infrastructure.engine.StateContext;
import com.rn.ddd.infrastructure.engine.annotation.OrderProcessor;
import com.rn.ddd.infrastructure.engine.constant.OrderEventEnum;
import com.rn.ddd.infrastructure.engine.constant.OrderStateEnum;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.List;

/**
 * 创建订单处理器
 *
 * @author 然诺
 * @date 2022/3/5
 */
@Slf4j
@OrderProcessor(states = {OrderStateEnum.INIT}, event = OrderEventEnum.CREATE, bizTypes = {"SHOP"}, sceneIds = "MOBILE")
public class CreateOrderProcessor extends AbstractStateProcessor<String, OrderBizContext> {

    @Resource
    private OrderRepository orderRepository;

    @Override
    public Result<String> check(StateContext<OrderBizContext> context) {
        OrderDO orderDO = (OrderDO) context.getOrder();
        // 检查订单是否存在
        boolean exist = orderRepository.exist(orderDO.getOrderName());
        if (exist) {
            return new Result<>(false, "1001");
        }
        return new Result<>(true);
    }

    @Override
    public OrderStateEnum getNextState(StateContext<OrderBizContext> context) {
        if (OrderEventEnum.CREATE.name().equals(context.getOrderEvent().getEventType())) {
            return OrderStateEnum.NEW;
        }
        return null;
    }

    @Override
    public Result<String> operate(StateContext<OrderBizContext> context, OrderStateEnum nextState) {
        // 生成订单编号
        return new Result<>(true);
    }

    @Override
    public Result<String> persistence(StateContext<OrderBizContext> context, OrderStateEnum nextState) {
        OrderDO orderDO = (OrderDO) context.getOrder();
        orderDO.setOrderState(nextState);
        return new Result<>(true);
    }

    @Override
    public Result<String> after(StateContext<OrderBizContext> context) {
        // 发送事件消息
        DomainEventPublisher.instance().publish(context.getOrderEvent());
        return new Result<>(true);
    }

    @Override
    public List<PluginHandler> getPlugins(StateContext<OrderBizContext> context) {
        return null;
    }
}
